package com.nhutcm.trackingthief.network;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;

import android.app.IntentService;
import android.content.Intent;

import com.nhutcm.trackingthief.R;
import com.nhutcm.trackingthief.receiver.TrackingThiefReceiver;
import com.nhutcm.trackingthief.utils.Constant;
import com.nhutcm.trackingthief.utils.InternetUtils;
import com.nhutcm.trackingthief.utils.PrefUtils;

/**
 * Lớp này có nhiệm vụ upload hình ảnh lên email, xóa hình sau khi up
 * 
 * @author Châu Minh Nhựt (nhutcm@viettel.com.vn)
 * 
 */
public class TrackingThiefNetwork extends IntentService {

	public static final String TAG = "com.nhutcm.trackingthief.service.TrackingThiefService";

	List<NameValuePair> params = new ArrayList<NameValuePair>();

	public TrackingThiefNetwork() {
		super("TrackingThiefService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		String filePath = intent
				.getStringExtra(TrackingThiefReceiver.FILE_PATH);

		Constant.mailTo = PrefUtils.readStringFromPreference(
				getApplicationContext(), getString(R.string.pref_email_key));

		if (InternetUtils.isConnectingToInternet(getApplicationContext())) {
			uploadImageToEmail(filePath, Constant.mailTo);
		}
	}

	private void uploadImageToEmail(String filePath, String email) {

		String path = TrackingThiefSendEmail.sending(filePath, email);
		if (path != null) {
			deleteImage(path);
		}
	}

	/**
	 * Xóa những hình ảnh đã chụp, vì đã upload lên mail rồi
	 * 
	 * @param filePath
	 */
	private void deleteImage(String filePath) {
		File file = new File(filePath);
		if (file.exists() && file.isFile()) {
			file.delete();
		}

	}
}
